package com.sanxiang.utils;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

public class TokenUtil {
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;  //有效时长
    private static final String TOKEN_SECRET = "wudixiaozu";       // 秘钥
    private static final Log log = LogFactory.get();

    /**
     * 签名 生成
     *
     * @parm managerId
     */
    public static String sign(Integer managerId) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("managerId", managerId.toString())
//                    .withExpiresAt(expiresAt)
                    //使用HMAC256算法加密
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     *
     * @param token
     */
    public static boolean verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
                    .withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            log.info("登录成功，managerId:{}", jwt.getClaim("managerId").asString());

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getId(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
        DecodedJWT jwt = verifier.verify(token);
        String id = jwt.getClaim("managerId").asString();
        return id;

    }

}
